package io.afu.validator.Implement;

import io.afu.validator.Annimation.ChineseWord;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChineseWordValidatorImpl implements ConstraintValidator<ChineseWord,String> {

    private Boolean allowEmpty;


    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (null == s || "".equals(s)){
            return this.allowEmpty;
        }else {
            String regex = "[\\u4e00-\\u9fa5]";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(s);
            return m.find();
        }
    }

    @Override
    public void initialize(ChineseWord constraintAnnotation) {
        this.allowEmpty = constraintAnnotation.allowEmpty();
    }
}
